package cn.edu.cqvie.netty.handler3.server;

import cn.edu.cqvie.netty.handler3.entity.PersonProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

public class MyServerHandler extends SimpleChannelInboundHandler<PersonProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonProtocol msg) throws Exception {


        System.out.println("服务端接收到的消息数据：");
        System.out.println("长度：" + msg.getLength());
        System.out.println("内容：" + new String(msg.getContent(), "utf-8"));

        System.out.println("服务端接收到的消息数量：" + (++this.count));


        String content = UUID.randomUUID().toString();
        int l = content.getBytes("utf-8").length;
        byte[] c = content.getBytes("utf-8");

        PersonProtocol personProtocol = new PersonProtocol();
        personProtocol.setLength(l);
        personProtocol.setContent(c);

        ctx.writeAndFlush(personProtocol);
    }

    /**
     * 出现异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
